package space.xxhui.javatts.base.system.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import space.xxhui.javatts.base.utils.IpAddressUtils;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Component
@WebFilter
public class HttpRequestLogFilter extends OncePerRequestFilter {
    private final Logger logger = LoggerFactory.getLogger(HttpRequestLogFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
            String requestId = request.getHeader("Request-Id");
            if (requestId == null) requestId = request.getRequestedSessionId();
            if (requestId == null) requestId = UUID.randomUUID().toString();
            logger.info("Request-Id: " + requestId);
            logger.info("URI: " + request.getRequestURL().toString());
            logger.info("RequestMethod: " + request.getMethod());
            logger.info("ClientIp: " + IpAddressUtils.getIpAddress(request));
            logger.info("Content-Type: " + request.getContentType());
            logger.info("UserAgent: " + request.getHeader("user-agent"));
        }
        filterChain.doFilter(request, response);
    }
}
